package com.hk.core.web.reactive.filters;

import com.hk.commons.util.StringEscapeHandler;
import com.hk.core.web.reactive.XssServerHttpRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.http.codec.FormHttpMessageReader;
import org.springframework.http.codec.HttpMessageReader;
import org.springframework.web.reactive.function.server.RequestPredicate;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author Kevin
 * @date 2022/11/28 22:47
 */
@RequiredArgsConstructor
public class XssFilter implements WebFilter {

    private final RequestPredicate requestPredicate;

    private final StringEscapeHandler stringEscapeHandler;

    private static final List<HttpMessageReader<?>> httpMessageConverters = List.of(new FormHttpMessageReader());

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        boolean matcher = requestPredicate.test(ServerRequest.create(exchange, httpMessageConverters));
        return matcher ? chain.filter(exchange.mutate()
                .request(new XssServerHttpRequest(exchange.getRequest(), stringEscapeHandler)).build())
                : chain.filter(exchange);
    }
}
